//
//  SystemConfig.swift
//  YYProject
//
//  Created by 陆文宇 on 2017/8/12.
//  Copyright © 2017年 陆文宇. All rights reserved.
//

import UIKit
import Alamofire
import Kingfisher
import Qiniu
import SnapKit
import RealmSwift

class System: UIResponder, GeTuiSdkDelegate, UNUserNotificationCenterDelegate {
    
    static let shared = System()
    
    static func logTPartVersionNumber() {
        yy_Log("AlamofireVersionNumber: \(AlamofireVersionNumber)")
        yy_Log("KingfisherVersionNumber: \(KingfisherVersionNumber)")
        yy_Log("QiniuVersionNumber: \(QiniuVersionNumber)")
        yy_Log("SnapKitVersionNumber: \(SnapKitVersionNumber)")
        yy_Log("RealmSwiftVersionNumber: \(RealmSwiftVersionNumber)")
    }
    
    static func configGeTui(appId: String, appKey: String, appSecret: String) {
        yy_Log("GeTui_Version" + GeTuiSdk.version())
        
        GeTuiSdk.runBackgroundEnable(true)
        GeTuiSdk.start(withAppId: appId, appKey: appKey, appSecret: appSecret, delegate: shared)
        
        registerRemoteNotification()
    }
    
    static func registerRemoteNotification() {
        /*
         警告：Xcode8的需要手动开启“TARGETS -> Capabilities -> Push Notifications”
         */
        
        /*
         警告：该方法需要开发者自定义，以下代码根据APP支持的iOS系统不同，代码可以对应修改。
         以下为演示代码，仅供参考，详细说明请参考苹果开发者文档，注意根据实际需要修改，注意测试支持的iOS系统都能获取到DeviceToken。
         */
        
        let systemVer = (UIDevice.current.systemVersion as NSString).floatValue
        if systemVer >= 10.0 {
            if #available(iOS 10.0, *) {
                let center = UNUserNotificationCenter.current()
                center.delegate = shared
                center.requestAuthorization(options: [.alert, .badge, .sound], completionHandler: { (granted, error) -> Void in
                    if error == nil {
                        yy_Log("NotificationCenter request authorization succeeded")
                    } else {
                        yy_Log("NotificationCenter request authorization failure: \(error!)")
                    }
                })
                UIApplication.shared.registerForRemoteNotifications()
            } else {
                let userSettings = UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)
                UIApplication.shared.registerUserNotificationSettings(userSettings)
                
                UIApplication.shared.registerForRemoteNotifications()
            };
        } else if systemVer >= 8.0 {
            let userSettings = UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)
            UIApplication.shared.registerUserNotificationSettings(userSettings)
            
            UIApplication.shared.registerForRemoteNotifications()
        }
    }
    
    static func configRealm(version: UInt64) {
        YYRealm.realmVersion = version
        
        yy_Log("Realm_Version: \(version)")
    }
    
    static func configBugly(appId: String) {
        yy_Log("Bugly_Version: " + Bugly.sdkVersion())
        
        let config = BuglyConfig()
        config.debugMode = false
        config.reportLogLevel = .info
        config.channel = "添衣汇商户端"
        config.version = UIApplication.yy_appVersion
        Bugly.start(withAppId: appId, config: config)
        Bugly.setUserIdentifier(YYAppConfig.getOne(key: appConfig_user_mobile) ?? "未登录")
    }
    
    static func configUMeng(appKey: String) {
        yy_Log("UMeng_Version: " + UMSocialGlobal.umSocialSDKVersion())
        
        UMSocialManager.default().openLog(true)
        UMSocialManager.default().umSocialAppkey = appKey
    }
    
    static func configUMeng_WX(appKey: String, appSecret: String) {
        UMSocialManager.default().setPlaform(UMSocialPlatformType.wechatSession, appKey: appKey, appSecret: appSecret, redirectURL: "http://mobile.umeng.com/social")
    }
    
    static func configUMeng_QQ(appKey: String, appSecret: String) {
        UMSocialManager.default().setPlaform(UMSocialPlatformType.QQ, appKey: appKey, appSecret: appSecret, redirectURL: "http://mobile.umeng.com/social")
    }
    
    static func configUMeng_Sina(appKey: String, appSecret: String) {
        UMSocialManager.default().setPlaform(UMSocialPlatformType.sina, appKey: appKey, appSecret: appSecret, redirectURL: "http://mobile.umeng.com/social")
    }
    
    static func configBMKMap(appKey: String) {
        let mapManager = BMKMapManager()
        yy_Log("BMKMapApi_Version: " + BMKGetMapApiVersion())
        yy_Log("BMKMapApi_BaseComponent_Version: " + BMKGetMapApiBaseComponentVersion())
        yy_Log("BMKMapApi_MapComponent_Version: " + BMKGetMapApiMapComponentVersion())
        yy_Log("BMKMapApi_LocationComponent_Version: " + BMKGetMapApiLocationComponentVersion())
        
        let ret = mapManager.start(appKey, generalDelegate: nil)
        if ret != true {
            yy_Log("manager start failed!");
        }
    }
    
    static func initCities() {
        let plistPath = Bundle.main.path(forResource: "cities", ofType: "plist")!
        let plistDic = NSDictionary(contentsOfFile: plistPath)!
        let version = plistDic["version"] as! String
        let cities = plistDic["cities"] as! [Any]
        
        if YYAppConfig.getOne(key: appConfig_version_city) == nil {
            YYCity.create(cities)
            YYAppConfig.set(key: appConfig_version_city, value: version)
        }
    }
    
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        yy_Log("willPresentNotification: \(notification.request.content.userInfo)");
        completionHandler([.badge,.sound,.alert]);
    }
    
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userinfo = response.notification.request.content.userInfo
        yy_Log("didReceiveNotificationResponse: \(userinfo)");
        GeTuiSdk.handleRemoteNotification(userinfo);
        if let payload = userinfo["payload"] as? String {
            dealGeTuiPayloadDic(try! JSONSerialization.yy_jsonObject(with: payload) as! [String : Any], offLine: true)
        }
        completionHandler();
    }
    
    func geTuiSdkDidRegisterClient(_ clientId: String!) {
        yy_Log("GeTuiSdk RegisterClient: " + clientId)
        
        handleGeTuiClientId(clientId)
    }
    
    func geTuiSdkDidOccurError(_ error: Error!) {
        yy_Log("GeTuiSdk error: " + error.localizedDescription)
    }
    
    func geTuiSdkDidSendMessage(_ messageId: String!, result: Int32) {
        yy_Log("GeTuiSdk DidSendMessage: sendmessage=\(messageId), result=\(result)")
    }
    
    func geTuiSdkDidReceivePayloadData(_ payloadData: Data!, andTaskId taskId: String!, andMsgId msgId: String!, andOffLine offLine: Bool, fromGtAppId appId: String!) {
        if !offLine {
            dealGeTuiPayloadData(payloadData, offLine: offLine)
        }
        yy_Log("GeTuiSdk DidReceivePayload: Receive Payload: \(String(data: payloadData, encoding: .utf8) ?? ""), taskId: \(taskId), messageId: \(msgId)")
    }

}
